import { getUserInfo, login } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { ElMessage } from 'element-plus'

export function handleLogin (userInfo: any) {
  const username = userInfo.account.trim()
  const password = userInfo.password
  return new Promise((resolve, reject) => {
    login(username, password)
      .then((res: any) => {
        setToken(res.data.accessToken)
        resolve(res)
      })
      .catch(error => {
        reject(error)
      })
  })
}

export function logoutSystem (showMsg: boolean = true): void {
  // 移除token
  removeToken()
  // 清空localStorage
  localStorage.clear()
  if (showMsg) {
    ElMessage.success('您已退出登录')
  }
}

export async function getAndSaveUserInfo () {
  // 获取用户信息
  let info = await getUserInfo()
  if (info.data.id) {
    localStorage.setItem('userInfo', JSON.stringify(info.data))
  } else {
    localStorage.removeItem('userInfo')
  }
}
